from util.Service import *
# 查询所有的菜单 （分页）
def getMenuAll():
    return Menu.getAllMenus()
# 查询所有的菜单 (分页 查询id 菜单名)
def getMenuName(page:Page = Page()):
    Menus = Menu.getAllMenuName(page)
    return Menus

# 修改菜单信息（除了mid）
def updateMenu(data:dict):
    try:
        id = data['mId']
        data = formatParam(data,['mId',"createTime"])
        if not authParam(data.get('status'),['1','0']):
            return False
        if not authParam(data.get('faceShow'),['1','0']):
            return False
        if not authParam(data.get('iconType'),['user','sys','none']):
            return False
        Menu.updateMenu(id,data)
        return True
    except :
        return False
# 添加菜单
def addMenu(data:dict):

    try:
        formatParam(data,['mId'])
        data['status'] = '1'
        data['faceShow'] = '1'
        data["createTime"]=datetime.utcnow()
        if not authParam(data['iconType'],['user','sys','none']):
            return False
        Menu.addMenu(data)
    except:
        return False
    return True

    
# 删除菜单 
def delMenu(mids:list[int]):
    # 在用户角色映射表中删除 mid 的映射关系
    database.transaction()
    try:
        with database.atomic():
            if Menu.MenuHasChild(mids):
                return '请先删除所选菜单下的子菜单'
            tags = Menu.getAllMenuHandleTags(mids)
            Menu.delMenuInMId(mids)
            Menu.delMenuHandleInMid(mids)
            Role.delRoleMenuHandleInTag(tags)
            Role.delRoleMenuInMid(mids)
            database.commit()
    except:
        database.rollback()
        return False
    return True
# 查询菜单上的所有按钮
def getMenuHandles(mid):
    return Menu.getAllMenuHandleInMids([mid])

# 更新菜单上的按钮   
def updataMenuHandles(mid:int,data:list[dict]):
    try:
        database.begin()
        # 提取旧标签
        oldTags = Menu.getAllMenuHandleTags([mid])
        Menu.delMenuHandleInMid([mid])
        data = formatParam(data,['id'])
        for d in data:
            d['mId'] = mid
            if(d.get('tag') in oldTags):
                oldTags.remove(d.get('tag'))
        # 删除已经不存在的映射关系
        Role.delRoleMenuHandleInTag(oldTags)
        Menu.addMenuHandle(data)
        database.commit()
        return True
    except Exception:
        database.rollback()
        assert Exception
        return False
     